import React, { useState, useEffect } from 'react';
import RGL, { WidthProvider } from '@/components/Draggler';
import _ from 'lodash';
import DragDom from '@/components/DragDom';
import { getHomeDetail } from '@/api/index';
import { getToken } from '@/utils/auth';
import { message } from 'antd';
const ReactGridLayout = WidthProvider(RGL);
const generateDOM = layout => {
  // eslint-disable-next-line complexity
  console.log(layout);

  return _.map(layout, (l, i) => {
    const nl = JSON.parse(l.cfiLayout);
    nl.static = true;

    return (
      <div key={nl.i} style={{ overflow: 'hidden' }} data-grid={nl}>
        <DragDom key={nl.i} data={l} isCs={false} isHome />
      </div>
    );
  });
};
export default () => {
  const [layout, setLayout] = useState([]);
  const [curlayout, setcurLayout] = useState([]);
  const [pageNo, setpageNo] = useState(1);

  useEffect(() => {
    getHomeDetail(getToken(), 1).then(res => {
      console.log('res', res);
      if (res.code === '0') {
        setLayout(res.data.list);
      } else {
        message.error(res.msg);
      }
    });
  }, []);
  return (
    // onDragEnter={() => setDo(true)} fix bug: 拖入一个item还没放置的时候触发onLayoutChange导致页面白板
    <div className="home-grid-box">
      <ReactGridLayout className="cst-layout" cols={12} rowHeight={30}>
        {generateDOM(layout)}
      </ReactGridLayout>
      <div className="pagenoBox" >
        <img src={require('../../assets/images/temp/pageChange.png')} style={{ cursor: pageNo > 1 ? 'pointer' : 'not-allowed' }} alt="" onClick={ e => {
          if (pageNo > 1){
            const page = pageNo - 1;
            setpageNo(page);
            getHomeDetail(getToken(),page).then(res => {
              setLayout(res.data.list);
            });
          }
        }} />
        <span>第{pageNo}页</span>
        <img src={require('../../assets/images/temp/pageChange.png')} style={{ cursor: pageNo < curlayout ? 'pointer' : 'not-allowed' }} className="nextPage" alt="" onClick={ e => {
          if (pageNo < curlayout){
            const page = pageNo + 1;
            setpageNo(page);
            getHomeDetail(getToken(),page).then(res => {
              setLayout(res.data.list);
            });
          }
          console.log(pageNo);
        }} />
      </div>
    </div>
  );
};
